﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using d1Common.WebController;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using d1Common;
using d1Project.Tools.PagedList;
using d1Project.Modules.Common.do4A.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;

namespace d1Project.Modules.Common.do4A.Controllers.a1
{
    [Route("do4A/a1/Role")]
    public class RoleController : Authorize1Controller
    {
        protected override DbContext dbContext
        {
            get
            {
                return this.db;
            }
        }
        private do4ADbContext db = new do4ADbContext();

        /// <summary>
        /// 查询角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [PermissionCheck(Id = "do4A$Role", Operation = 0)]
        public async Task<IHttpActionResult> Get([FromUri]RoleGetVm model)
        {
            var role = db.Roles.AsQueryable();

            if (!string.IsNullOrEmpty(model.Name))
            {
                role = role.Where(p => p.Name.Contains(model.Name));
            }

            var result = await role.OrderBy(p => p.CreateTime).ToPagedListAsync(model);
            return Ok(new { total = role.Count(), rows = result });
        }

        [PermissionCheck(Id = "do4A$Role", Operation = 0)]
        public async Task<IHttpActionResult> Get(string Id)
        {
            var entity = await db.Roles.FindAsync(Id);
            return Ok(entity);
        }

        [PermissionCheck(Id = "do4A$Role", Operation = 1)]
        public async Task<IHttpActionResult> Post(Role model)
        {

            var entity = await db.Roles.Where(p => p.Name == model.Name).FirstOrDefaultAsync();
            if (entity != null)
            {
                this.Error("该用角色已存在");
            }
            Role role = new Role();
            role.Id = doServices.Instance.DoCore.getGUID();
            role.Name = model.Name.Trim();
            role.CreateById = this.UserId;
            role.CreateByName = this.UserName;
            role.CreateTime = DateTime.Now;
            role.UpdateTime = DateTime.Now;
            db.Roles.Add(role);
            await db.SaveChangesAsync();
            return Ok();
        }

        [PermissionCheck(Id = "do4A$Role", Operation = 2)]
        public async Task<IHttpActionResult> Put(Role model)
        {
            if (string.IsNullOrEmpty(model.Id))
            {
                this.Error("Id不能为空");
            }
            var entity = await db.Roles.Where(p => p.Name == model.Name && p.Id != model.Id).FirstOrDefaultAsync();
            if (entity != null)
            {
                this.Error("该用角色已存在");
            }
            var role = db.Roles.FirstOrDefault(p => p.Id == model.Id);
            role.Name = model.Name;
            role.UpdateById = this.UserId;
            role.UpdateByName = this.UserName;
            role.UpdateTime = DateTime.Now;
            await db.SaveChangesAsync();
            return Ok();
        }

        [PermissionCheck(Id = "do4A$Role", Operation = 4)]
        public async Task<IHttpActionResult> Delete(string id)
        {
            if (string.IsNullOrEmpty(id)) this.Error("id不能为空");

            var role = await db.Roles.FindAsync(id);
            if (role == null) this.Error("角色信息未找到");
            db.Roles.Remove(role);

            var rolePermissions = db.RolePermissions.Where(x => x.RoleId == id).ToList();
            if (rolePermissions.Count() > 0) db.RolePermissions.RemoveRange(rolePermissions);

            await db.SaveChangesAsync();
            return Ok();
        }
    }

    public class RoleGetVm : VmBase
    {
        public string Name { get; set; }
    }
}